#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

'''
文件名称：main.py
创 建 者：yang qiang
创建日期：2019年08月15日
描    述：
Copyright (C) 2019 All rights reserved.
'''

class NumMatrix(object):

    def __init__(self, matrix):
        """
        :type matrix: List[List[int]]
        """
        self.row = len(matrix)
        if self.row != 0:
            self.col = len(matrix[0])
        else:
            return

        self.local_matrix = [ [0] * (self.col+1) for i in range(0, self.row+1) ]

        for i in range(self.row - 1, -1, -1):
            for j in range(self.col - 1, -1, -1):
                self.local_matrix[i][j] = self.local_matrix[i+1][j] + self.local_matrix[i][j+1] + matrix[i][j] - self.local_matrix[i+1][j+1]
        

    def sumRegion(self, row1, col1, row2, col2):
        """
        :type row1: int
        :type col1: int
        :type row2: int
        :type col2: int
        :rtype: int
        """
        if self.row == 0:
            return 0

        if row1 < 0 or row2 >= self.row:
            return 0

        if col1 < 0 or col2 >= self.col:
            return 0

        return self.local_matrix[row1][col1] - self.local_matrix[row1][col2+1] - self.local_matrix[row2+1][col1] + self.local_matrix[row2+1][col2+1]
